<?php
/**
 * 官网活动ajax类快速下单
 * @package  ajax
 * @subpackage  shop
 * @author   allen.qiang@fistforward.com
 */

quanli_require('module/base/customer/quanliCust.class.php');
quanli_require('module/base/activity/activitySpike.class.php');
quanli_require('module/base/shop/shopCart.class.php');
quanli_require('module/base/activity/activityConfig.class.php');

final class ajax_speedBill {

    private $pcustID;//会员号:int
    private $custID;//会员名/手机号:int

    private $start_time;//活动开始时间:datetime
    private $end_time;//活动技术时间:datetime

    private $config;//活动配置

    private $debug = false;//开启调试

    public function __construct(){

        if (!isset($_REQUEST['operFlg']) || empty($_REQUEST['operFlg'])) {
            returnJsonData('参数错误');
        }

        global $G_SHOP;

        $config_code = trim($_REQUEST['operFlg']);

        //实例化配置类
        $activity_config = new activityConfig($config_code);

        $config_array =  $activity_config->config;

        if($config_array){

            $this->config = $config_array;

            $this->start_time = $config_array['start_time'];
            $this->end_time = $config_array['end_time'];

            if(isset($config_array['debug']) && $_REQUEST['debug']=='1'){
                $this->debug = true;
            }

        }else{
            returnJsonData('活动不存在');
        }

        if(!$G_SHOP->currentCustomerID){
            returnJsonData('尚未登陆');
        }

        $this->pcustID =  $G_SHOP->currentPCustID;//用户ID
        $this->custID =  $G_SHOP->currentCustomerID;//手机号

        unset($G_SHOP,$activity_config,$config_array);

    }

    public function execute() {

        if(date('Y-m-d H:i:s') < $this->start_time){
            returnJsonData('活动未开始');
        }

        if(date('Y-m-d H:i:s') > $this->end_time){
            returnJsonData('活动已结束');
        }

        //检查用户
        $this->checkUser();

        //检查用过购买
        $this->checkUserBuy();

        $cityId = intval($_REQUEST['city_id']);
        $sendDate = trim($_REQUEST['send_date']);

        //检查配送量
        $this->checkBillNum($cityId,$sendDate);

        $config = $this->config;

        $bill = array();

        $bill['deliver_provinceid'] = $this->getProvinceID($cityId); //省
        $bill['deliver_cityid'] = $cityId;  //市
        $bill['custID'] = $this->custID; //用户ID/手机号
        $bill['country'] = $_REQUEST['country']; //区id
        $bill['deliver_name'] = $_REQUEST['deliver_name']; //收货人
        $bill['deliver_address'] = $_REQUEST['deliver_address'];//收货人地址
        $bill['deliver_mobile'] = $_REQUEST['deliver_mobile'];//收货人手机
        $bill['is_the_invoice'] = $_REQUEST['is_the_invoice'];//是否需要发票
        $bill['invoice_title_type'] = $_REQUEST['invoice_title_type'];//1：个人 2：单位
        $bill['invoice_title'] = $_REQUEST['invoice_title']; //发票抬头
        $bill['payTypeID'] = $config['pay_type_id']; //支付方式ID
        $bill['payment_method_id'] = $config['payment_method_id']; //付款方式
        $bill['send_date'] = $_REQUEST['send_date'];//配送日期

        $send_time = explode('-',$_REQUEST['send_time']);

        $bill['send_start_time'] = $send_time[0];//配送开始时间
        $bill['send_end_time'] = $send_time[1];//配送结束时间
        $bill['billPromotion'] = $this->config['billPromotion'];//促销渠道

        $bill['invoice_type'] = 1; //发票类型： 1、商业零售发票
        $bill['invoice_content'] = null;//发票内容
        $bill['invoice_amount'] = 1; //发票金额
        $bill['invoice_number'] = null;//发票号
        $bill['is_urgent'] = 3;
        $bill['remark'] = '';
        $bill['billChannel'] = 1;
        $bill['billType'] = 1;
        $bill['external_bill_no'] = null;

        //创建订单
        $result = $this->create_bill($bill);

        $data = isset($result['data'])?$result['data']:'';

        returnJsonData( $result['message'],$result['code'],$data);

    }

    //创建订单
    private function create_bill($bill) {

        global $G_SHOP;

        $config = $this->config;

        $goods_array[] = array(
            'sku' => $config['sku'],
            'num' => $config['sku_max_num']
        );

        quanli_require('module/base/customer/quanliCust.class.php');
        quanli_require('module/base/customer/custDeliver.class.php');
        quanli_require('module/base/customer/custInvoice.class.php');
        quanli_require('module/base/system/sysRegion.class.php');
        quanli_require('module/base/system/sysDistribution.class.php');
        quanli_require('module/base/system/sysPayment.class.php');
        quanli_require('module/base/bill/billCheckout.class.php');
        quanli_require('module/base/system/sysSend.class.php');
        quanli_require('module/base/goods/quanliGoods.class.php');

        $quanliGoods = new quanliGoods( $G_SHOP->DBCA );
        $quanliCust = new quanliCust();
        $custDeliver = new custDeliver();
        $custInvoice = new custInvoice();
        $sysDistribution = new sysDistribution();
        $sysPayment = new sysPayment();
        $billCheckout = new billCheckout();
        $sysSend = new sysSend();
        $sysRegion = new sysRegion( $G_SHOP->DBCA );

        $args_array = array(
            'custID' => $bill['custID']
        );
        $customer_array = $quanliCust->searchCustomerDetail( $args_array );

        /**
         * =====================
         * 省市区查询
         * =====================
         */
        $args_array = array(
            'id' => $bill['deliver_provinceid'],
            'region_level' => 1
        );
        $province_array = $sysRegion->getAreaManageList( $args_array );
        $args_array = array(
            'id' => $bill['deliver_cityid'],
            'region_level' => 2
        );
        $city_array = $sysRegion->getAreaManageList( $args_array );
        $args_array = array(
            'id' => $bill['country'],
            'region_level' => 3
        );
        $county_array = $sysRegion->getAreaManageList( $args_array );

        /**
         * ================
         * 收货地址
         * ================
         */
        $args_array = array(
            'pcustID' => $customer_array['pcustID'],
            'creator' => $bill['custID'],
            'custName' => $bill['deliver_name'],
            'provinceid' => $province_array[0]['id'],
            'cityid' => $city_array[0]['id'],
            'countyid' => $county_array[0]['id'],
            'address' => $bill['deliver_address'],
            'mobile' => $bill['deliver_mobile'],
            'phone' => ''
        );

        $deliver_array_s = $custDeliver->searchCustDeliver( $args_array );

        if($deliver_array_s)
        {
            $deliver_array = $deliver_array_s[0];
        }
        else
        {
            $result_deliver = $custDeliver->editCustDeliver( $args_array );
            if ($result_deliver['code'] != 200) {
                return $result_deliver;
            }
            else
            {
                $deliver_array = $result_deliver['data'];
            }
        }

        /**
         * ================
         * 发票
         * ================
         */
        if ($bill['invoice_title_type']) {
            $args_array = array(
                'creator' =>$bill['custID'],
                'pcustID' => $customer_array['pcustID'],
                'invoice_type' => $bill['invoice_type'],
                'invoice_title_type' => $bill['invoice_title_type'],
                'invoice_title' => $bill['invoice_title'],
            );
            $result_array = $custInvoice->editCustInvoice( $args_array );
            if ($result_array['code'] == 200) {
                $invoice_array = $result_array['data'];
            }
        }

        /**
         * ================
         * 查询配送站
         * ================
         */
        $areaID = $billCheckout->getMapArea( $deliver_array['longitude'], $deliver_array['latitude'], $city_array[0]['id'], 1);

        if($areaID['areaID'] == 0)
        {
            return array('code'=>404,'message'=>'抱歉,该地址不属于免费配送区域!');
        }

        //查询地图区域和配送站的映射关系
        $args_array = array(
            'areaID' => $areaID['areaID']
        );
        $distribution_map_area = $sysDistribution->searchDistributionMapArea( $args_array );
        if($distribution_map_area) {
            $distribution_id = $distribution_map_area[0]['distribution_id'];
        }

        if (isset($distribution_id)) {
            //查询配送站
            $args_array = array(
                'distribution_id' => $distribution_id,
                'useFlg' => 1
            );
            $distribution_array = $sysDistribution->search( $args_array );
        }

        /**
         * ================
         * 查询配送方式
         * ================
         */
        $result_array = $billCheckout->getMapArea( $deliver_array['longitude'], $deliver_array['latitude'], $city_array[0]['id'], 2);
        $areaID = $result_array['areaID'];
        if ($areaID == 0) {
            $areaID = $result_array['default_areaID'];
        }

        //查询地图区域下的所有配送区域
        $args_array = array(
            'areaID' => $areaID
        );
        $send_area_array = $sysSend->searchSendArea( $args_array );
        if (!$send_area_array) {
            return $send_area_array;
        }

        //根据配送区域查询配送方式
        $args_array = array(
            'sendTypeID' => $send_area_array[0]['sendTypeID']
        );
        $sendType_array = $sysSend->searchSendType( $args_array );

        if($send_area_array[0]['freight'] > 0)
        {
            return array('code'=>404,'message'=>'抱歉,该地址不属于免费配送区域!');
        }

        $bill_no = generate_seqno('seqno_bill');
        $bill_code = $city_array[0]['alias'] . get_bill_code( 'seqno_bill_code' . $city_array[0]['alias'] );

        /**
         * ================
         * 查询支付方式
         * ================
         */
        $pay_type_array = $sysPayment->searchPayTypeDetail( $bill['payTypeID'] );

        if (!$pay_type_array) {
            return $pay_type_array;
        }

        if ($pay_type_array['type'] == 1 ) {
            if (!isset($bill['payment_method_id']) || !quanli_is_int($bill['payment_method_id'])) {
                return array('code'=>404,'message'=>'支付方式不存在');
            }
            $args_array = array(
                'id' => $bill['payment_method_id']
            );

            $payment_array = $sysPayment->searchPaymentMethod( $args_array );

            if (!$payment_array) {
                returnJsonData('支付方式不存在', 404);
            }
        }

        $bill_totalMoney = 0;//订单总金额,根据商品的标准售价计算出的，不含运费
        $bill_totalPaid = 0;//订单商品实际成交金额,不含运费，不含附加费
        $bill_accessories_money = 0; //订单配件金额
        $bill_subtract_money = 0; //订单立减金额
        $bill_coupon_money = 0; //订单优惠券订单金额
        $bill_card_money = 0; //代金卡抵扣金额
        $bill_paying_agent_money = 0; //代付订单总金额
        $bill_points_money = 0; //订单总积分价格??????
        $bill_balance_money = 0; //余额抵扣金额
        $bill_online_money = 0; //在线支付已付金额
        $deliver_fee = $send_area_array[0]['freight']; //运费
        $deliver_feePaid = $deliver_fee; //实收运费

        $bill_totalAmount = 0;

        //临时数组
        $temp_array = array(
            'pay_id' => array(),
            'pay_name' => array(),
            'goods' => array(),
            'coupon_code' => array(),
            'card_code' => array(),
            'paying_agent_str' => array()
        );

        /**
         * ===================
         * 订单商品
         * ===================
         */
        $bill_goods_array = array();

        $bill_goods_fittings_array = array();

        $tableware_amount = 0;

        $candle_amount = 0;

        foreach($goods_array as &$goods) {

            $args_array = array(
                'product_code' => $goods['sku'],
            );
            $goods_info = $quanliGoods->searchGoodsSaleDetail( $args_array );
            if (!$goods_info) {
                return  array(
                    'code' => 404,
                    'message' => '没有商品' . $goods['sku']
                );
            }

            $bill_goods_obj = new entity('bill_goods');
            $bill_goods_obj->creator = $bill['custID'];
            $bill_goods_obj->bill_no = $bill_no;
            $bill_goods_obj->bill_goods_no = generate_seqno('seqno_bill_goods');
            $bill_goods_obj->goods_goodsID = $goods_info['goodsID'];
            $bill_goods_obj->goods_postID = $goods_info['postID'];
            $bill_goods_obj->product_code = $goods_info['product_code'];
            $bill_goods_obj->goods_name = $goods_info['goodsName'];
            $bill_goods_obj->goods_spec = $goods_info['spec'];
            $bill_goods_obj->goods_amount = 1;
            $bill_goods_obj->goods_marketPrice = $goods_info['marketPrice'];
            $bill_goods_obj->goods_storePrice = $goods_info['salePrice'];
            $bill_goods_obj->goods_purchasePrice = $goods_info['salePrice'];
            $bill_goods_obj->goods_pointsPrice = 0;
            $bill_goods_obj->goods_points = 0;
            $bill_goods_obj->goods_weight = 0;
            $bill_goods_obj->goods_from = 1;
            $bill_goods_obj->goods_groupID = 0;
            $bill_goods_obj->goods_remark = isset($goods['goods_remark']) ? $goods['goods_remark'] : null;
            $bill_goods_obj->birthday_card = isset($goods['birthday_card']) ? $goods['birthday_card'] : null;
            $bill_goods_obj->segmentation = isset($goods['segmentation']) ? $goods['segmentation'] : 0;
            $bill_goods_array[] = $bill_goods_obj;
            $bill_totalAmount++;

            $bill_totalMoney += $bill_goods_obj->goods_storePrice;
            $bill_totalPaid += $bill_goods_obj->goods_purchasePrice;
            $temp_array['goods'][] = $goods_info['product_code'] . ',' . $goods_info['goodsName'];

        }

        //订单金额
        $bill_money = $bill_totalPaid + $bill_accessories_money + $deliver_feePaid + $bill_paying_agent_money;

        //订单应收金额
        $bill_receivable_money = $bill_money - $bill_subtract_money - $bill_coupon_money - $bill_card_money - $bill_balance_money - $bill_points_money - $bill_online_money;

        $bill_pay_array = array();

        //保存订单支付信息
        $pay_status = 0;
        if ($bill_receivable_money >= 0) {

            if ($bill_receivable_money == 0) {
                $pay_status = 2;
            }

            $bill_pay_obj = new entity('bill_pay');
            $bill_pay_obj->creator = $bill['custID'];
            $bill_pay_obj->bill_no = $bill_no;
            $bill_pay_obj->payTypeID = $pay_type_array['payTypeID'];
            $bill_pay_obj->payTypeName = $pay_type_array['payTypeName'];
            $bill_pay_obj->type = $pay_type_array['type'];
            $bill_pay_obj->pay_amount = $bill_receivable_money;
            if ($pay_type_array['type'] == 1) {
                $bill_pay_obj->deduct_amount = 0;
                $bill_pay_obj->payment_method_id = $payment_array[0]['id'];
                $bill_pay_obj->payment_method_name = $payment_array[0]['name'];
                $bill_pay_obj->payment_method_type = $payment_array[0]['type'];
            } else {
                $bill_pay_obj->deduct_amount = 0;
            }

            $bill_pay_array[] = $bill_pay_obj;

            $temp_array['pay_id'][] = $pay_type_array['payTypeID'];
            $temp_array['pay_name'][] = $pay_type_array['payTypeName'];

        }

        $bill_master = new entity('bill_master');
        $bill_master->creator = $bill['custID'];
        if (!empty($bill['createTime'])) {
            $bill_master->createTime = $bill['createTime'];
        }

        if($pay_type_array['type'] == 1 && isset($payment_array))
        {
            $bill_master->payment_method_id =  $payment_array[0]['id'];
            $bill_master->payment_method_name = $payment_array[0]['name'];

        }
        $bill_master->bill_no = $bill_no;
        $bill_master->bill_code = $bill_code;
        $bill_master->pcustID = $customer_array['pcustID'];
        $bill_master->custID = $customer_array['custID'];
        $bill_master->bill_status = 0 ;//状态已确认
        $bill_master->billPromotion = $bill['billPromotion'];

        $bill_master->bill_totalMoney = $bill_totalMoney;
        $bill_master->bill_totalPoints = round($bill_money / 4);
        $bill_master->bill_accessories_money = $bill_accessories_money;
        $bill_master->bill_paying_agent_money = $bill_paying_agent_money;
        $bill_master->bill_subtract_money = $bill_subtract_money;
        $bill_master->bill_coupon_money = $bill_coupon_money;
        $bill_master->bill_pointsPrice = 0;
        $bill_master->bill_money = $bill_money;
        $bill_master->bill_totalPaid = $bill_totalPaid;
        $bill_master->bill_card_money = $bill_card_money;
        $bill_master->bill_balance_money = $bill_balance_money;
        $bill_master->bill_points_money = $bill_points_money;
        $bill_master->bill_online_money = $bill_online_money;
        $bill_master->bill_receivable_money = $bill_receivable_money;
        $bill_master->bill_received_money = $bill_money - $bill_receivable_money;

        $bill_master->deliverid = $deliver_array['deliverID'];
        $bill_master->deliver_name = encryptD($deliver_array['custName']);
        $bill_master->deliver_province = $deliver_array['provinceName'];
        $bill_master->deliver_provinceid = $deliver_array['provinceid'];
        $bill_master->deliver_city = $deliver_array['cityName'];
        $bill_master->deliver_cityid = $deliver_array['cityid'];
        $bill_master->deliver_county = $deliver_array['countyName'];
        $bill_master->deliver_countyid = $deliver_array['countyid'];
        $bill_master->deliver_address = encryptD($deliver_array['address']);
        $bill_master->deliver_mobile = encryptD($deliver_array['mobile']);
        $bill_master->deliver_phone = encryptD($deliver_array['phone']);
        $bill_master->send_date = $bill['send_date'];
        $bill_master->send_start_time = $bill['send_start_time'];
        $bill_master->send_end_time = $bill['send_end_time'];
        if (isset($distribution_array)) {
            $bill_master->distribution_id = $distribution_array[0]['distribution_id'];
            $bill_master->distribution_name = $distribution_array[0]['distribution_name'];
        }
        if (isset($distribution_technicia_array)) {
            $bill_master->distribution_technician_id = $distribution_technicia_array[0]['distribution_technician_id'];
            $bill_master->distribution_technicia = $distribution_technicia_array[0]['distribution_technicia'];
        }
        $bill_master->sendTypeID = $sendType_array[0]['sendTypeID'];
        $bill_master->sendTypeName = $sendType_array[0]['sendTypeName'];
        $bill_master->send_region_id = $send_area_array[0]['send_region_id'];
        $bill_master->send_region_name = $send_area_array[0]['send_region_name'];
        $bill_master->pay_type = $pay_type_array['type'];
        $bill_master->payTypeID = $pay_type_array['payTypeID'];
        $bill_master->payTypeName = $pay_type_array['payTypeName'];
        $bill_master->pay_status = $pay_status;
        $bill_master->remark = $bill['remark'];
        $bill_master->billPlatform = 1;
        $bill_master->billChannel = $bill['billChannel'];
        $bill_master->billType = $bill['billType'];
        if ($bill['invoice_title_type']) {
            $bill_master->invoice = 1;
            $bill_master->invoiceID = $invoice_array['invoiceID'];
        } else {
            $bill_master->invoice = 0;
            $bill_master->invoiceID = 0;
        }
        $bill_master->invoice_type = 1;
        $bill_master->invoice_title_type = $bill['invoice_title_type'];
        $bill_master->invoice_title = $bill['invoice_title'];
        $bill_master->invoice_content = $bill['invoice_content'];
        $bill_master->invoice_amount = $bill['invoice_amount'];
        $bill_master->invoice_number = $bill['invoice_number'];
        $bill_master->is_the_invoice = $bill['is_the_invoice'];
        $bill_master->is_urgent = $bill['is_urgent'];
        $bill_master->external_bill_no = $bill['external_bill_no'];
        $bill_master->bill_totalAmount = $bill_totalAmount;
        $bill_master->deliver_fee = $deliver_fee;
        $bill_master->deliver_feePaid = $deliver_feePaid;
        $bill_master->tableware_amount = $tableware_amount;
        $bill_master->candle_amount = $candle_amount;
        $bill_master->pay_name_str = implode(',', $temp_array['pay_name']);
        $bill_master->pay_id_str = implode(',', $temp_array['pay_id']);
        $bill_master->goods_name_str = implode(',', $temp_array['goods']);
        $bill_master->coupon_code = implode(',', $temp_array['coupon_code']);
        $bill_master->card_code = implode(',', $temp_array['card_code']);
        $bill_master->paying_agent_str = implode(',', $temp_array['paying_agent_str']);

        /**
         * 内部留言
         */
        $bill_remark_array = array();
        if (isset($bill['remark']) && !empty($bill['remark'])) {

            foreach($bill['remark'] as &$remark) {
                $bill_remark_obj = new entity('bill_remark');
                $bill_remark_obj->creator = $bill['custID'];
                $bill_remark_obj->createTime = $remark['createTime'];
                $bill_remark_obj->bill_no = $bill_no;
                $bill_remark_obj->remark = $remark['remark'];
                $bill_remark_array[] = $bill_remark_obj;
            }

        }

        try {

            $G_SHOP->DBCA->beginTransaction();

            //保存订单主表
            $G_SHOP->DBCA->save($bill_master);

            //保存订单商品
            foreach($bill_goods_array as &$goods_obj) {

                if ($bill_master->bill_status > 0) {

                    $bill_goods_product = new entity('bill_goods_product');
                    $bill_goods_product->timeStamp = $G_SHOP->sys_datetime;
                    $bill_goods_product->creator = $bill['custID'];
                    $bill_goods_product->createTime = $G_SHOP->sys_datetime;
                    $bill_goods_product->bill_no = $goods_obj->bill_no;
                    $bill_goods_product->bill_goods_no = $goods_obj->bill_goods_no;
                    $bill_goods_product->bill_code = $bill_master->bill_code;
                    $bill_goods_product->cityID = $bill_master->deliver_cityid;
                    $bill_goods_product->cityName = $bill_master->deliver_city;
                    $bill_goods_product->billType = $bill_master->billType;
                    $bill_goods_product->send_date = $bill_master->send_date;
                    $bill_goods_product->send_start_time = $bill_master->send_start_time;
                    $bill_goods_product->send_end_time = $bill_master->send_end_time;
                    $bill_goods_product->distribution_id = $bill_master->distribution_id;
                    $bill_goods_product->distribution_name = $bill_master->distribution_name;
                    $bill_goods_product->is_urgent = $bill_master->is_urgent;
                    $bill_goods_product->goods_postID = $goods_obj->goods_postID;
                    $bill_goods_product->product_code = $goods_obj->product_code;
                    $bill_goods_product->goods_name = $goods_obj->goods_name;
                    $bill_goods_product->goods_spec = $goods_obj->goods_spec;
                    $bill_goods_product->goods_amount = $goods_obj->goods_amount;
                    $bill_goods_product->tableware_amount = $goods_obj->tableware_amount;
                    $bill_goods_product->extra_tableware_amount = $goods_obj->extra_tableware_amount;
                    $bill_goods_product->candle_amount = $goods_obj->candle_amount;
                    $bill_goods_product->extra_candle_amount = $goods_obj->extra_candle_amount;
                    $bill_goods_product->birthday_card = $goods_obj->birthday_card;
                    $bill_goods_product->segmentation = $goods_obj->segmentation;
                    $bill_goods_product->goods_remark = $goods_obj->goods_remark;
                    $G_SHOP->DBCA->save($bill_goods_product);

                }

                $G_SHOP->DBCA->save($goods_obj);

            }

            foreach($bill_goods_fittings_array as &$fit_obj) {
                $G_SHOP->DBCA->save($fit_obj);
            }

            //保存订单支付
            foreach($bill_pay_array as &$pay_obj) {
                $G_SHOP->DBCA->save($pay_obj);
            }

            if (!empty($bill_remark_array)) {
                foreach($bill_remark_array as &$remark_obj) {
                    $G_SHOP->DBCA->save($remark_obj);
                }
            }

            $G_SHOP->DBCA->commit();


            //查询支付方式信息
            $args_array = array(
                'payTypeID' => $bill['payTypeID']
            );
            $pay_typ_array = $sysPayment->searchPayType( $args_array );
            $shop_array['pay_logo'] = $pay_typ_array[0]['logo_img'];

            //查询在线支付参数
            $online_parameter_array = $sysPayment->searchOnlinepPrameter( $bill['payTypeID'] );
            $online_parameter_array['bill_no'] = $bill_no;
            $online_parameter_array['pcustID'] = $bill['pcustID'];
            $online_parameter_array['payTypeID'] = $bill['payTypeID'];
            $online_parameter_array['payTypeName'] = $pay_type_array['payTypeName'];
            $online_parameter_array['pay_amount'] = $bill_receivable_money;
            $online_parameter_array['bill_code'] = $bill_code;
            $online_parameter_array['subsite'] = 'shop';


            //加载在线支付接口文件，生成支付请求链接
            include ( sprintf('onlinepay/%s/send.php', $online_parameter_array['alias']) );



            if (isset($requestURL)) {
                $shop_array['requestURL'] = $requestURL;
            } else {
                $shop_array['requestForm'] = $requestForm;
            }

            $requestURL = isset($requestURL)?$requestURL:$requestForm;

            return array(
                'code' => 200,
                'message' => 'ok',
                'data'=>array(
                    'bill_no' => $bill_no,
                    'bill_code' => $bill_code,
                    'pay_link' => $requestURL
                )
            );


        } catch (Exception $e) {

            $G_SHOP->DBCA->rollBack();

            if ($e->getCode() > 0) {
                return array(
                    'code' => $e->getCode(),
                    'message' => $e->getMessage()
                );

            } else {
                error_log($e->getMessage());
                return array(
                    'code' => 500,
                    'message' => '系统错误'
                );
            }

        }

    }

    //检查是否活动页注册用户
    private function checkUser(){

        global $G_SHOP;

        $config_array = $this->config;

        $custID = $this->custID;

        $custSource_ext = $config_array['activityNumber'];

        $sql = "SELECT custSource_ext FROM cust_master WHERE custID = '{$custID}'";

        $result = $G_SHOP->DBCA->stmt_query($sql);

        if($result){
            //判断是否活动页面注册用户
            if($result[0]->custSource_ext != $custSource_ext){
                //400（身份验证错误）
                returnJsonData( '本次活动仅针对本活动页首次注册的MCAKE会员',400);
            }else{
                //200（成功）
                return array(
                    'code' => 200,
                    'message' => '成功'
                );
            }
        }else{
            //404（未找到）
            returnJsonData( '用户尚未注册',404);
        }

    }

    //检查用户是否购买过
    private function checkUserBuy(){

        global $G_SHOP;

        $custID = $this->custID;

        $sql = "SELECT COUNT(uuid) AS num FROM bill_master WHERE bill_status != 10 AND custID = '{$custID}'";

        $result = $G_SHOP->DBCA->stmt_query($sql);

        if($result[0]->num > 0){
            //400（不接受）
            returnJsonData( '不符合活动条件</br>请阅读活动规则',400);
        }else{
            //200（成功）
            return array(
                'code' => 200,
                'message' => 'ok'
            );
        }
    }

    //检查是否达到配送上限
    private function checkBillNum($cityID,$sendDate){

        global $G_SHOP;

        $config = $this->config;

        $billPromotion = $config['billPromotion'];

        //每日配送量
        $sendNum = 0;

        $sendNumArr = explode(',',$config['send_num']);

        foreach($sendNumArr as $txt){
            $arr = explode(':',$txt);
            if($arr[0]==$cityID){
                $sendNum += $arr[1];
                break;
            }
        }

        $sql = "SELECT COUNT(uuid) AS num FROM bill_master WHERE deliver_cityid = '{$cityID}' AND billPromotion = '{$billPromotion}' AND send_date = '{$sendDate}'";

        $result = $G_SHOP->DBCA->stmt_query($sql);

        if($result[0]->num >= $sendNum){
            //403（不接受）
            returnJsonData( '配送量超额，无法配送订单，请选择其他日期。',403);
        }else{
            //200（成功）
            return array(
                'code' => 200,
                'message' => 'ok'
            );
        }
    }

    //生成付款链接
    private function createPayLink(){
        //实例支付方式类
        $sysPayment = new sysPayment();


        //查询支付方式信息
        $args_array = array(
            'payTypeID' => $bill['payTypeID']
        );
        $pay_typ_array = $sysPayment->searchPayType( $args_array );
        $shop_array['pay_logo'] = $pay_typ_array[0]['logo_img'];

        //查询在线支付参数
        $online_parameter_array = $sysPayment->searchOnlinepPrameter( $bill['payTypeID'] );
        $online_parameter_array['bill_no'] = $bill['bill_no'];
        $online_parameter_array['pcustID'] = $bill['pcustID'];
        $online_parameter_array['payTypeID'] = $bill['payTypeID'];
        $online_parameter_array['payTypeName'] = $bill['payTypeName'];
        $online_parameter_array['pay_amount'] = $bill['bill_receivable_money'];
        $online_parameter_array['bill_code'] = $bill['bill_code'];
        $online_parameter_array['subsite'] = 'shop';
        if (isset($cps_info_array) && $cps_info_array[0] == 'shanghai') {
            $online_parameter_array['auth_code'] = $cps_info_array[4];
        }

        //加载在线支付接口文件，生成支付请求链接
        include ( sprintf('onlinepay/%s/send.php', $online_parameter_array['alias']) );

        if (isset($requestURL)) {
            $shop_array['requestURL'] = $requestURL;
        } else {
            $shop_array['requestForm'] = $requestForm;
        }
    }

    //根据城市ID获取省份ID
    public function getProvinceID($cityID){

        global $G_SHOP;

        $sql = "SELECT parentID FROM sys_region WHERE id = {$cityID}";

        $result = $G_SHOP->DBCA->stmt_query($sql);

        return $result[0]->parentID;

    }
}

?>